﻿

using DynamicCode;
using DynamicCode.Compilation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Simple1
    {
        public static void Run()
        {

            DynamicCodeBuilder dynamicWorker = new DynamicCodeBuilder(codetemplate, typeof(ProductEntity), "entity");
            Type[] types = dynamicWorker.Grenerate(dBEntities.Select(n => new DynamicCodeItem { Code = n.Code, Content = n.Content }).ToArray());
            ProductEntity entity = new ProductEntity() { Price = 9, Quantity = 5 };
            var instances = types.Select(n => System.Activator.CreateInstance(n)).OfType<IWorker>();

            Console.WriteLine("Init Moeny:{0} Quantity:{1} Tax:{2}", entity.Moeny, entity.Quantity, entity.Tax);

            foreach (var instance in instances)
            {
                instance.Invoke(entity);
                Console.WriteLine("Run {3} after:\r\n       Moeny:{0} Quantity:{1} Tax:{2}", entity.Moeny, entity.Quantity, entity.Tax, instance.GetType().Name);
            }

        }
        const string codetemplate = @" 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Math;  

        public class @code@Worker:ConsoleApp1.IWorker
        {
            public void Invoke(ConsoleApp1.ProductEntity entity)
            {
                @content@                
            }
        } 
";
        static DBEntity[] dBEntities = new[]{
                    new  DBEntity(){Code = "A1",Content = "@Moeny@ = @Quantity@ + @Price@ ;\r\n@Tax@ = 3 ; "},
                    new  DBEntity(){Code = "B1",Content = "@Quantity@ =  @Quantity@ * 3;"},
                    new  DBEntity(){Code = "C1",Content = "@Moeny@ += @Quantity@ +  Round(@Price@ * 0.13m,2);"}
                };

        /*
         实现过程流程
         1：     业务伪代码
                 content "@Moeny@ = @Quantity@ + @Price@ ;\r\n@Tax@ = 3 ; "


         2：        找出content 的变量，并得出将要替换成的内容
                 { "@Moeny@", "entity.Moeny" },
                 { "@Quantity@", "entity.Quantity" },
                 { "@Price@", "entity.Price" }
                 { "@Tax@", "entity.Tax" }

         3：      content 转换成下面业务代码
                  entity.Moeny = entity.Quantity +  entity.Price ;
                  entity.Tax = 3 ;
         
         */
    }
    public interface IWorker
    {
        void Invoke(ProductEntity product);
    }
}
